package com.lzm.ydpt.module.order.activity;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.view.View;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TextView;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;
import androidx.recyclerview.widget.RecyclerView;

import com.amap.api.maps2d.model.LatLng;
import com.amap.api.services.core.PoiItem;
import com.byt.framlib.base.BaseActivity;
import com.byt.framlib.baseadapter.rv.RvCommonAdapter;
import com.byt.framlib.baseadapter.rv.RvViewHolder;
import com.byt.framlib.basemvp.basebean.ListPageBean;
import com.byt.framlib.basemvp.boby.FormBodys;
import com.byt.framlib.commonutils.rx.RxBus;
import com.byt.framlib.commonwidget.OnNoDoubleClickListener;
import com.byt.framlib.commonwidget.onclicktwo.AntiShake;
import com.byt.framlib.commonwidget.refresh.RefreshHeaderView;
import com.lzm.ydpt.Constants;
import com.lzm.ydpt.Dapplication;
import com.lzm.ydpt.R;
import com.lzm.ydpt.entity.AddressBook;
import com.lzm.ydpt.entity.AddressBookBus;
import com.lzm.ydpt.module.common.MapAddressActivity;
import com.lzm.ydpt.mvp.contract.FillAddressContract;
import com.lzm.ydpt.mvp.presenterimpl.FillAddressPresenterImpl;
import com.scwang.smartrefresh.layout.api.RefreshLayout;
import com.scwang.smartrefresh.layout.listener.OnRefreshLoadMoreListener;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;

/**
 * 填写地址
 */
public class FillAddressActivity extends BaseActivity<FillAddressPresenterImpl> implements FillAddressContract.View {

    private static final int ADDRESS_CODE = 0x02;

    @BindView(R.id.ll_history_address_layout)
    LinearLayout ll_history_address_layout;
    @BindView(R.id.srf_history_address)
    RefreshLayout srf_history_address;
    @BindView(R.id.rv_history_address)
    RecyclerView rv_history_address;

    @BindView(R.id.ed_address_username)
    EditText ed_address_username;
    @BindView(R.id.ed_address_phone)
    EditText ed_address_phone;
    @BindView(R.id.tv_address_region)
    EditText tv_address_region;
    @BindView(R.id.tv_select_region)
    TextView tv_select_region;
    @BindView(R.id.ed_detailed_address)
    EditText ed_detailed_address;

    /**
     * 1 发货地址
     * 2 送货地址
     */
    private int type = 1;
    private AddressBook mAddressBook = null;
    private int pageNum = 1;
    private RvCommonAdapter<AddressBook> mRvAdapter = null;
    private List<AddressBook> mList = new ArrayList<>();
    private PoiItem mPoiItem = null;
    private LatLng mLatLng = null;

    @Override
    public int getLayoutId() {
        return R.layout.activity_fill_address;
    }

    @Override
    public FillAddressPresenterImpl initPreData() {
        return new FillAddressPresenterImpl(this);
    }

    @Override
    public void initView() {
        type = getIntent().getIntExtra(Constants.INP_FILL_ADDRESS_TYPE, 1);
        initRv();
        initAdapter();
        initData();
    }

    private void initRv() {
        setRefreshLayout(srf_history_address);
        srf_history_address.setRefreshHeader(new RefreshHeaderView(this).getHeaderStyleStaffF4());
        srf_history_address.setOnRefreshLoadMoreListener(new OnRefreshLoadMoreListener() {
            @Override
            public void onLoadMore(@NonNull RefreshLayout refreshLayout) {
                pageNum++;
                getHistoryAddressList();
            }

            @Override
            public void onRefresh(@NonNull RefreshLayout refreshLayout) {
                pageNum = 1;
                getHistoryAddressList();
            }
        });
    }

    private void initData() {
        if (mAddressBook != null) {
            ed_address_username.setText(mAddressBook.getContacts());
            ed_address_phone.setText(mAddressBook.getPhone());
            tv_address_region.setText(mAddressBook.getAddress());
            ed_detailed_address.setText(mAddressBook.getDetailedAddress());
            mLatLng = new LatLng(mAddressBook.getLatitude(), mAddressBook.getLongitude());
        }
    }

    private void getHistoryAddressList() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("memberId", Dapplication.getUserInfo().getMemberId());
        formBodys.add("type", type);
        formBodys.add("pageSize", 10);
        formBodys.add("pageNum", pageNum);
        mPresenter.onHistoryAddressList(formBodys.build());
    }

    private void initAdapter() {
        rv_history_address.setLayoutManager(new LinearLayoutManager(this));
        mRvAdapter = new RvCommonAdapter<AddressBook>(this, mList, R.layout.item_history_address_rv) {
            @Override
            protected void convert(RvViewHolder holder, AddressBook addressBook, int position) {
                holder.setText(R.id.tv_user_mail_info, addressBook.getContacts() + "  " + addressBook.getPhone());
                holder.setText(R.id.tv_user_mail_address, addressBook.getAddress());
                holder.getConvertView().setOnClickListener(new OnNoDoubleClickListener() {
                    @Override
                    protected void onNoDoubleClick(View v) {
                        mAddressBook = addressBook;
                        initData();
                    }
                });
            }
        };
        rv_history_address.setAdapter(mRvAdapter);
    }

    @OnClick({R.id.tv_select_address_book})
    public void OnClick(View v) {
        if (AntiShake.check(v.getId())) {
            return;
        }
        switch (v.getId()) {
            case R.id.tv_select_address_book:
                Bundle bundle = new Bundle();
                bundle.putInt(Constants.INP_ADDRESS_MANAGER_TYPE, 1);
                openActivity(AddressBookActivity.class, bundle);
                break;
            case R.id.ll_select_region:
                Bundle addressBundle = new Bundle();
                addressBundle.putParcelable(MapAddressActivity.INP_POIITEMS_INFO, mLatLng);
                startActivityForResult(MapAddressActivity.class, addressBundle, ADDRESS_CODE);
                break;
            case R.id.add_save_addess:
                if (isCheck()) {
                    addAddressBook();
                }
                break;
        }
    }

    private boolean isCheck() {
        if (TextUtils.isEmpty(ed_address_username.getText().toString())) {
            showShortToast("请输入联系人");
            return false;
        }
        if (TextUtils.isEmpty(ed_address_phone.getText().toString())) {
            showShortToast("请输入手机号");
            return false;
        }
        if (TextUtils.isEmpty(tv_address_region.getText().toString())) {
            showShortToast("请选择地址");
            return false;
        }
        if (TextUtils.isEmpty(ed_detailed_address.getText().toString())) {
            showShortToast("请输入门牌号");
            return false;
        }
        return true;
    }

    private void addAddressBook() {
        FormBodys.Builder formBodys = new FormBodys.Builder();
        formBodys.add("memberId", Dapplication.getUserInfo().getMemberId());
        formBodys.add("type", type);
        formBodys.add("contacts", ed_address_username.getText().toString());
        formBodys.add("phone", ed_address_phone.getText().toString());
        formBodys.add("address", tv_address_region.getText().toString());
        formBodys.add("detailedAddress", ed_detailed_address.getText().toString());

        if (mLatLng == null) {
            if (mAddressBook != null) {
                formBodys.add("id", mAddressBook.getId());
                formBodys.add("longitude", mAddressBook.getLongitude());
                formBodys.add("latitude", mAddressBook.getLatitude());
            }
        } else {
            formBodys.add("longitude", mLatLng.longitude);
            formBodys.add("latitude", mLatLng.latitude);
        }
        startProgressDialog();
        mPresenter.onFillAddress(formBodys.build());
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            if (requestCode == ADDRESS_CODE) {
                PoiItem mPoiItem = data.getParcelableExtra(MapAddressActivity.INP_POIITEMS_INFO);
                if (mPoiItem != null) {
                    this.mPoiItem = mPoiItem;
                    mLatLng = new LatLng(mPoiItem.getLatLonPoint().getLatitude(), mPoiItem.getLatLonPoint().getLongitude());
                }
                tv_address_region.setText(mPoiItem.getProvinceName() + mPoiItem.getCityName() + mPoiItem.getAdName());
                ed_detailed_address.setText(mPoiItem.getTitle());
                ed_detailed_address.setSelection(ed_detailed_address.length());
                tv_select_region.setText(mPoiItem.getCityName());
            }
        }
    }

    @Override
    public void onFillAddress(String msg) {
        stopProgressDialog();
        showShortToast(msg);
        RxBus.getDefault().postSticky(new AddressBookBus());
        finish();
    }

    @Override
    public void onHistoryAddressList(ListPageBean<AddressBook> addressBookList) {
        if (pageNum == 1) {
            mList.clear();
            srf_history_address.finishRefresh();
        } else {
            srf_history_address.finishLoadMore();
        }
        mList.addAll(addressBookList.getList());
        mRvAdapter.notifyDataSetChanged();
        srf_history_address.setEnableLoadMore(addressBookList.getList().size() >= 10);
        ll_history_address_layout.setVisibility(mList.size() == 0 ? View.INVISIBLE : View.VISIBLE);
    }

    @Override
    public void showMessage(String message, String method) {
        stopProgressDialog();
        showShortToast(message);
    }

    @Override
    public void showErrorView(String msg) {

    }
}